Accessibility
Home / DevNet / ColdFusion Development Center /
DevNet
ColdFusion Article
Icon or Spacer Icon or Spacer Icon or Spacer
Samuel Neff
 
Samuel Neff
Senior Software Engineer
www.blinex.com
 
Learning Stored Procedure Basics in ColdFusion MX

Most ColdFusion applications center around a database. The key to creating efficient and secure ColdFusion applications is ensuring that all database interaction are both efficient and secure. Stored procedures help developers accomplish both of these goals and also accomplish greater abstraction between the application code and database details. In this article, we’ll explore stored procedures and review a few examples using Oracle, Microsoft SQL Server (MSSQL), and Microsoft Access.

What Is a Stored Procedure?
A stored procedure is a set of Structured Query Language (SQL) statements that you assign a name to and store in a database in compiled form so that you can share it between a number of programs.

Stored procedures can contain not only simple select, insert, update, and delete statements, but also can encapsulate procedural code. Since you compile and encapsulate stored procedures, they provide more efficient and secure data access.

Whenever you run a query statement against a database, the database performs two functions. First, it compiles the statement and then it executes it. During compilation the database engine breaks the query apart, identifies the tables and relationships, determines which indexes to use and when to combine and filter records. For example, see the execution plan in Figure 1.

Figure 1.  The execution plan.

Figure 1. The execution plan for a simple query occurs each time with a query, but only once with a stored procedure. Click the image to see a larger version of the execution plan.

This execution plan shows a simple query that combines data from five tables using outer joins. With a standard query from a ColdFusion cfquery tag, the database engine recompiles the statement each time it executes the query. With a stored procedure, however, the database compiles the query plan once and reuses the compiled process. This pre-compilation yields a significant performance advantage.

Encapsulating Database Code to Simplify and Secure Database Transactions
Stored procedures also help developers encapsulate database code. By placing all database access and manipulation code inside stored procedures, you create lots of little black boxes. Instead of a team of ColdFusion developers having to be familiar with the database schema, indexes, and columns, they simply need to know the names of stored procedures, which an experienced DBA can write and optimize. For example, a ColdFusion page might have a poorly written cross-tab query, as shown in Listing 1.

Listing 1. A query that performs a cross-tab style query against an Oracle database through ColdFusion.
<CFQUERY NAME="getCrossTabData" DATASOURCE="ORATEST">
  SELECT
    DV1.State_ID,
    DV1.Data_Year,
    DV1.Data_Value AS Val1,
    DV2.Data_Value AS Val2
  FROM
      Data_Values DV1,
      Data_Values DV2
  WHERE
        DV1.State_ID = DV2.State_ID
    AND DV1.Data_Year = DV2.Data_Year
    AND DV1.Data_Year BETWEEN #yearStart# AND #yearEnd#
    AND DV1.Field_ID = 1000
    AND DV2.Field_ID = 1001
  ORDER BY
    DV1.State_ID,
    DV1.Data_Year
</CFQUERY>

If you instead use a stored procedure to perform the same select, it simplifies the ColdFusion code, as shown in Listing 2.

Listing 2. Using a cfstoredproc tag to perform the same cross-tab style query shown in Listing 1.
<CFSTOREDPROC PROCEDURE="pkg_Simple.sp_Get_Values" DATASOURCE="oratst">
  <CFPROCPARAM 
    DBVARNAME="Start_Year" 
    VALUE="#yearStart#" 
    CFSQLTYPE="cf_sql_numeric">
  <CFPROCPARAM 
    DBVARNAME="End_Year" 
    VALUE="#yearEnd#" 
    CFSQLTYPE="cf_sql_numeric">
  <CFPROCRESULT 
    NAME="getCrossTabData">
</CFSTOREDPROC>
Encapsulating the database interaction provides a number of benefits:
  • It simplifies the ColdFusion code. Instead of using a large query in your application, you simply call a stored procedure.
  • It allows you to optimize SQL queries in a central location. With all SQL stored centrally in a database, you can appoint a DBA to write or optimize queries. In this case, your DBA may choose to rewrite the above statement using only a single instance of the database table and an Oracle specific function, DECODE, to generate the cross-tab data.
  • It achieves greater security. The link between stored procedures and security is not always obvious. A stored procedure limits specific functionality based on required, type-specific input parameters. Setting these limits is central in helping you take advantage of the security features in stored procedures.

    If you write an application so that all database interactions occur through stored procedures, then you can limit the access that a specific database username and password (entered into ColdFusion Administrator for the application) has so that it can only run stored procedures. With this safeguard, anyone who gains access to your database or ColdFusion server can only perform very few tasks with such limited access.

Creating Stored Procedures
The section below reviews several sample stored procedures in both Oracle and MSSQL. To follow along, download the table creation scripts, which create the tables and columns and insert data.

Download storedprocedures.zip (33K).

Refer to the documentation for your database to learn how to execute the scripts. Typically, to execute the scripts in Oracle, you use SQL Plus. In SQL Server, you use the Query Analyzer.

At this time, also create your data sources for Oracle and SQL Server data sources. Name your Oracle data source "oratst" and name your SQL Server data source "sqltst".

Developing Stored Procedure Development on a Budget
While the last part of this tutorial demonstrates stored procedure using with Microsoft Access, Access supports only an extremely limited syntax for stored procedures. To truly learn how to use stored procedures effectively, you should have access to a more robust database, such as Oracle, MSSQL, or PostgreSQL. If none of these are available to you, MSDE may be a good option for experimenting and even full-scale developing.

MSDE is a desktop version of MSSQL, appropriate for developing and using in staging environment. Microsoft Office 2000 includes Microsoft Data Engine 1.0 and is compatible with MSSQL 7, while Microsoft Office XP includes Microsoft SQL Server 2000 Desktop Engine and is compatible with MSSQL 2000.

The following links provide more information on installing and setting up MSDE.

Inserting Data with Stored Procedures
In the first example, you'll learn to create a stored procedure that inserts new records into the Books table shown in Figure 2.

Figure 2. The Books table.
Figure 2. The Books table.


The table has four columns; three information fields, and a BookID (its primary key). The stored procedure will accept three input parameters and return one output parameter, the newly inserted BookID. See the stored procedures for both Oracle and MSSQL below in listings 3 and 4. Typically, you execute your stored procedures in SQL Plus in Oracle and Query Analyzer in SQL Server. For more information on executing queries and stored procedures, refer to your database documentation.

Listing 3. Stored procedure to insert data into the Books table in Oracle.
CREATE OR REPLACE PROCEDURE sp_Insert_Book (
  arg_Title Books.Title%type,
  arg_Price Books.Price%type,
  arg_PublishDate Books.PublishDate%type,
  arg_BookID OUT Books.BookID%type)
AS
  num_BookID NUMBER;
BEGIN
  
  SELECT seq_Books.NEXTVAL
  INTO num_BookID
  FROM DUAL;
    
  INSERT INTO
    Books (
      BookID,
      Title,
      Price,
      PublishDate )
  VALUES (
    num_BookID,
    arg_Title,
    arg_Price,
    arg_PublishDate );
  
  arg_BookID := num_BookID;
  
END;
/

In MSSQL, create the stored procedure that will insert data into the Books table.

  1. Start Query Analyzer and connect to your MSSQL server instance.
  2. Select your test database from the database pop-up menu in the toolbar.
  3. Paste Listing 4 (below) into the blank script window.
  4. Click the Execute Query button on the toolbar (green arrow).
  5. The confirmation message, "The command(s) completed successfully." appears in the messages window below the script window.
Listing 4. The MSSQL stored procedure you will paste in step 3 above.
CREATE PROCEDURE sp_Insert_Book (
  @arg_Title VARCHAR(255),
  @arg_Price SMALLMONEY,
  @arg_PublishDate DATETIME,
  @arg_BookID INT OUT)
AS
BEGIN
  
  INSERT INTO
    Books (
      Title,
      Price,
      PublishDate )
  VALUES (
    @arg_Title,
    @arg_Price,
    @arg_PublishDate );
  
  SELECT @arg_BookID = @@IDENTITY;
  
END;

Both stored procedures perform the same function but require slightly different syntax. Oracle has a beneficial feature that allows you to specify data types for procedures so they match a field type using the following syntax: [Table Name].[Field Name]%type. MSSQL uses a simpler mechanism for inserting incremental values, which means the same procedure requires half the code for this simple routine.

While the stored procedure syntax is different, one big benefit of stored procedures is that the ColdFusion MX code that calls a stored procedure is exactly the same regardless of DBMS. Listing 5 shows a ColdFusion page that inserts books into the database using the stored procedure and confirm that the insert succeeded.

Listing 5. ColdFusion MX code inserts a book into a database and confirms the insert with the user. You can copy and paste this code into your own CFML page to see the results. Comment out the data source you are not using.
<cfset ds = "sqltst">
<!--- <cfset ds = "oratst"> --->

<!---
      If submitting a new book,
      insert the record and display
      confirmation --->
<cfif isDefined("form.title")>
  
  <cfstoredproc procedure="sp_Insert_Book" datasource="#ds#">
    
    <cfprocparam 
      dbvarname="arg_Title"  
      cfsqltype="cf_sql_varchar"
      value="#form.title#">
      
    <cfprocparam
      dbvarname="arg_Price"
      cfsqltype="cf_sql_numeric"
      value="#form.price#">
      
    <cfprocparam
      dbvarname="arg_PublishDate"
      cfsqltype="cf_sql_date"
      value="#form.price#">
      
    <cfprocparam
      dbvarname="arg_BookID"
      cfsqltype="cf_sql_numeric"
      type="out"
      variable="bookId">
      
  </cfstoredproc>
  
  <cfoutput>
    <h3>'#form.title#' inserted into database.  The ID is #bookId#.</h3>
  </cfoutput>
  
</cfif>

<cfform action="#CGI.SCRIPT_NAME#" method="post">
  <h3>Insert a new book</h3>
  
  Title: 
  <cfinput 
    type="text" 
    size="20" 
    required="yes" 
    name="title"/>
  <br/>
  
  Price: 
  <cfinput 
    type="text" 
    size="20" 
    required="yes" 
    name="price" 
    validate="float" />
  <br/>
  
  Publish Date: 
  <cfinput 
    type="text" 
    size="5" 
    required="yes"  
    name="publishDate" 
    validate="date" />
  <br/>
  
  <input type="submit" value="Insert Book"/>
    
</cfform>
To call a stored procedure, you use two ColdFusion MX tags: cfstoredproc and cfprocparam. The cfstoredproc tag starts the call to the database and wraps the related tags. At a minimum, the tag requires the procedure and datasource attributes, which specify the stored procedure you wish to call and the data source to use for the call.

Use the cfprocparam tag to both pass parameters to a stored procedure and to specify variable names for output parameters. The example above uses the dbvarname attribute to match parameters by name instead of by position. The cfsqltype attribute is always required and specifies the data type for the parameter. To input parameters, include the value attribute with the passed value. Alternatively, if you wanted to pass a null value instead, you could include the null attribute.

For the output parameter, you again use the cfprocparam tag, specifying the type attribute value as out, and provide a ColdFusion variable name in the variable attribute. While in this page, you only display the Book ID to the user, but you could use the ID to also add authors and publishers to the book record with additional programming.

Returning Recordsets from Stored Procedures
In listings 3 and 4, you created stored procedures that accepted arguments and returned simple values. Stored procedures can also return database records. The procedures in listings 6 and 7 return book details based on a title search.

Listing 6. Stored procedure that searches for books in an Oracle data source.
CREATE OR REPLACE PACKAGE pkg_Search
AS

  TYPE CUSTOM_REF_CURSOR IS REF CURSOR;
  
  PROCEDURE sp_By_Title (
    arg_Title Books.Title%type,
    arg_Cursor IN OUT CUSTOM_REF_CURSOR);

END;
/

CREATE OR REPLACE PACKAGE BODY pkg_Search
AS

  PROCEDURE sp_By_Title (
    arg_Title Books.Title%type,
    arg_Cursor IN OUT CUSTOM_REF_CURSOR)
  IS
  BEGIN
      
    OPEN arg_Cursor FOR
    SELECT
      BookID,
      Title,
      Price,
      PublishDate
    FROM
      Books
    WHERE
      Title LIKE '%' || arg_Title || '%';        
  
  END;

END;
/
Listing 7. Stored procedure that searches for books in a MSSQL data source.
CREATE PROCEDURE sp_Search_By_Title (
  @arg_Title VARCHAR(255))
as
BEGIN
    
  SELECT
    BookID,
    Title,
    Price,
    PublishDate
  FROM
    Books
  WHERE
    Title LIKE '%' + @arg_Title + '%';        

END;
 

Notice first in this example that the Oracle example is long for the amount of work it does. Oracle returns records to the calling application through a reference cursor. However, you cannot directly use a reference cursor (REF CURSOR) in a stored procedure; instead you must declare a custom type within a package—which is a collection of stored procedures and functions, similar to a ColdFusion component (CFC).

All Oracle packages have two parts, the package header and the package body. The header includes type declarations and stored procedure headers. The stored procedure details are then placed in the package body using the syntax shown in listing 6, above.

Again, you can use similar code to call both stored procedures, as shown in listing 8. The only difference in the call for Oracle and MSSQL is the stored procedure name, since the Oracle procedure is a part of a package and MSSQL does not support packages.

 
<cfset ds = "oratst">
<cfset sp = "pkg_Search.sp_By_Title">
<!---
<cfset ds = "sqltst">
<cfset sp = "sp_Search_By_Title">
--->

<cfoutput>
  <form action="#cgi.SCRIPT_NAME#" method="post">
    <input type="text" name="criteria" size="20" />
    <input type="submit" value="Search"/>
  </form>
</cfoutput>

<cfif isDefined("form.criteria") AND form.criteria NEQ "">
  
  <cfstoredproc procedure="#sp#" datasource="#ds#">
    
    <cfprocparam
      dbvarname="arg_Title"
      cfsqltype="cf_sql_varchar"
      value="#form.criteria#">
    
    <cfprocresult
      name="searchResults">
      
  </cfstoredproc>
  
  <cfoutput>
    <h3>Search results for '#form.criteria#'</h3>
  </cfoutput>
  <cfdump var="#searchResults#" label="Search Results">
    
</cfif>
Listing 8 provides a small form for users to enter search criteria; the form then passes the search criteria to the database. The listing uses cfoutput to print the results to the screen.
Figure 3. The search results from the Stored Procedure.
Figure 3. The search results from the Stored Procedure.


The stored procedure call uses one new tag, cfprocresult, to provide a ColdFusion variable name for the recordset returned from the stored procedure. Since a stored procedure may return multiple recordsets, ColdFusion allows multiple cfprocresult tags within a single cfstoredproc tag.

Stored Procedures with Microsoft Access
While Microsoft Access doesn’t have a procedural SQL language like to Oracle or MSSQL, you can use stored procedures with MS Access to run simple queries and even pass parameters. This setup still allows you to take advantage of pre-compiled queries and also set up security so that a data source username and password only has access to execute stored procedures.

Listing 8 is a stored procedure for Microsoft Access. This is the same stored procedure for inserting data, as shown in listings 3 and 4.

Listing 8. Microsoft Access stored procedure for inserting a book record.
INSERT INTO
    Books (
      Title,
      Price,
      PublishDate )
VALUES (
    [arg_Title],
    [arg_Price],
    [arg_PublishDate] );

To create and use a stored procedure in Microsoft Access, do the following:

  1. In a Microsoft Access database, create a query named "sp_Insert_Book" in Design View
  2. Switch to SQL View.
  3. Paste the query in Listing 8.
  4. Save the query.
  5. Create a CFML page in your webroot.
  6. Paste the code in listing 5 in your CFML page. You must remove the last cfprocparam tag and the output for the Book ID, since the Access stored procedure does not return the newly inserted Book ID.
  7. Browse your CFML page.
  8. Check your database and you will see your inserted record.

Stored procedures provide a number of advantages over storing queries in ColdFusion pages. Pre-compiling SQL helps your application execute pages faster, and the encapsulating SQL within a database allows you to specialize database development and increase security. Using stored procedures is simple in ColdFusion MX and you should consider using them for all database-centric applications.

 


About the author
Samuel Neff is a Senior Software Engineer with B-Line Express, a custom software development company in Columbia, MD where he develops applications in ColdFusion, Java, and Macromedia Flash. He is an active member of the ColdFusion and Macromedia Flash communities and a Team Macromedia volunteer.

Submit feedback on our tutorials, articles, and sample applications.